package edu.rit.teamrocket.model;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class LogCollection implements LogDAO
{
	final String FILE_NAME = "logCollection.log";

	private List<DailyLog> logs;
	

	public LogCollection()
	{
		logs = new ArrayList<DailyLog>();
		logs = getLog();
	}

	public void addToLog(DailyLog log, Entry entry, int numberOfUnits) 
	{
		log.addToLog(entry, numberOfUnits);
	}

	public void addLog(DailyLog log)
	{
		if (!logs.contains(log))
			logs.add(log);
		saveLog();
		//System.out.println(logs.toString());
	}

	public List<DailyLog> getLogs() 
	{
		return logs;
	}

	public DailyLog findLog(int weight, Date date) 
	{
		for (DailyLog log : logs)
		{
			if ((log.getWeight() == weight) && (log.getDate() == date))
				return log;
		}
		return null;
	}

	@Override
	public void removeLog(DailyLog dailyLog) 
	{
		if (logs.contains(dailyLog))
			logs.remove(dailyLog);
	}

	public void saveLog()
	{
		File file = new File(FILE_NAME);
		if(file != null)
		{
			try
			{
				FileOutputStream out = new FileOutputStream(file, true); 
				ObjectOutputStream objectsOut = new ObjectOutputStream(out);
				//for(int i = 0; i < logs.size(); i++) 
				//{
					//objectsOut.writeObject(logs.get(i));
				//}
				objectsOut.writeObject(logs);
				objectsOut.flush(); 
				objectsOut.close();
				out.close();

			} 

			catch (Exception exception) 
			{
				System.err.println("Something went wrong: " + exception.getStackTrace());
			} 
		} 
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<DailyLog> getLog()
	{
		try
		{
			File f = new File(FILE_NAME);
			if(!f.exists()){
				f.createNewFile();
			}
			FileInputStream in = new FileInputStream(f);
			ObjectInputStream objectsIn = new ObjectInputStream(in);
			//while((object  = (DailyLog) objectsIn.readObject()) != null)
			//{
				//DailyLog objects = (DailyLog) objectsIn.readObject();
				//logs.add(objects);
			//}	
			
			logs = (List<DailyLog>) objectsIn.readObject();
			objectsIn.close();
			in.close();

		} catch(EOFException e) {
			//e.printStackTrace();
			return logs;
		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}

		return logs;
	}

	@Override
	public void DailyLog()
	{
		// TODO Auto-generated method stub

	}
}
